using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Authentication
/// </summary>
public class Authentication
{
	public Authentication()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /// <summary>
    /// This method will create a new user in the MSModerators database
    /// Returns 0 if the secret is wrong
    /// 1 if the user was created (SUCCESS)
    /// 2 if the user already exists
    /// </summary>
    /// <param name="username">Desired username</param>
    /// <param name="password">Desired password</param>
    public int CreateNewUser(string username, string password, string secret)
    {
        if (secret == "F0rumM0ds")
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MSModerators"].ConnectionString);
            connection.Open();
            //first, figure out if the given user exists, so we don't make two users with the same username;
            SqlCommand command = new SqlCommand("SELECT password from Users WHERE UserName = '" + username + "'", connection);
            SqlDataReader reader = command.ExecuteReader();
            if (!reader.HasRows)
            {
                reader.Close();
                command = new SqlCommand("INSERT INTO Users VALUES (NEWID(),'" + username + "','" + password + "',CONVERT(DateTime, '" + DateTime.Now.ToString() + "',121))", connection);
                command.ExecuteNonQuery();
                connection.Close();
                return 1;
            }
            else
                return 2;
        }
        else
            return 0;
    }

    /// <summary>
    /// This method authenticates a user, and passes back their "token" which should be used for calling other
    /// web services from msmoderators.com.  During this method, the token on the server is updated, along with
    /// its expiration date.
    /// </summary>
    /// <param name="username">Username</param>
    /// <param name="password">Password</param>
    /// <returns>A authentication token as a string, or the empty string if the user doesn't exist or the password'
    /// is incorrect</returns>
    public string Login(string username, string password)
    {
        string serverPassword;
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MSModerators"].ConnectionString);
        connection.Open();
        SqlCommand command = new SqlCommand("SELECT Password FROM Users WHERE UserName = '" + username + "'", connection);
        SqlDataReader reader = command.ExecuteReader();
        //if the user was found, read from the SQLDataReader.  Else, return an empty string
        if (reader.Read())
        {
            serverPassword = reader.GetString(0);
            reader.Close();
        }
        else
            return String.Empty;

        //if the user's password matches the input password, return the authentication token, else return the empty string
        if (password == serverPassword)
        {
            //update the UID and read it in again, and update the expirationdate of the token
            DateTime expireTime = DateTime.Now.AddHours(2.0);
            command = new SqlCommand("UPDATE Users SET UID = NEWID(), ExpirationDate = CONVERT(DateTime, '" + expireTime.ToString() + "', 121) WHERE UserName = '" + username + "'", connection);
            command.ExecuteNonQuery();
            command = new SqlCommand("SELECT UID FROM Users WHERE UserName = '" + username + "'", connection);
            reader = command.ExecuteReader();
            if (reader.Read())
            {
                Guid UID = reader.GetGuid(0);
                return UID.ToString();
            }
            else
                return String.Empty;
        }
        else
            return String.Empty;
    }

    /// <summary>
    /// This method takes a token and validates that it is a registered token in the user database
    /// </summary>
    /// <param name="token">Client-supplied token.</param>
    /// <returns>true if the token is valid, false otherwise</returns>
    public bool ValidateToken(string token)
    {
        Guid UID = new Guid(token);
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MSModerators"].ConnectionString);
        connection.Open();
        SqlCommand command = new SqlCommand("SELECT ExpirationDate FROM Users WHERE UID = '" + token + "'", connection);
        SqlDataReader reader = command.ExecuteReader();
        //if the ExpirationDate for the token has expired or the UID hasn't been found, return false, else return true
        if (reader.Read())
        {
            DateTime time = reader.GetDateTime(0);
            if (time > DateTime.Now)
                return true;
            else
                return false;
        }
        else
            return false;
    }
}
